package io.github.talelin.latticy.drools;

import io.github.talelin.latticy.util.JDBCUtil;

import java.io.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @authoer:wulongbo
 * @createDate:2022/8/8
 * @description:
 */
public class DroolsInput2DB {
    public static void main(String[] args) throws IOException {
        create();
    }

    public static void create() throws IOException {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            // 2.建立连接
            conn = JDBCUtil.getConnection();
            // 3.创建语句
            String sql = "insert into rules(rule) values(?)";
            ps = conn.prepareStatement(sql);
            //将该目录下的文件内容写到数据库的rules表中
            File file = new File("E:\\lin\\lin-cms-spring-boot-master\\src\\main\\resources\\rules\\bookDiscount.drl");
            Reader reader = new BufferedReader(new FileReader(file));
            //将“？”代替成数据流
            ps.setCharacterStream(1, reader, file.length());

            // 4.执行语句
            ps.executeUpdate();
            reader.close();

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.close(conn, ps, rs); // 关闭资源
        }
    }

    public static String getDrl(String id) {
        Connection connection = JDBCUtil.getConnection();
        ResultSet set = null;
        PreparedStatement statement = null;
        StringBuilder sb = new StringBuilder();
        try {

            String sql = "SELECT rule FROM rules where id =" + id;
            statement = connection.prepareStatement(sql);
            set = statement.executeQuery();
            while (set.next()) {
                Reader reader = set.getCharacterStream(1);
                //创建缓存区
                char[] buff = new char[1024];
                //读写数据方式1
                int len = 0;
                while ((len = reader.read(buff)) > 0) {
                    sb.append(buff, 0, len);
                }
                reader.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.close(connection, statement, set); // 关闭资源
        }
        return sb.toString();
    }
}
